/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.messaging.webqueue

import org.ibiblio.terasaur.bencode.Bencode
import org.ibiblio.terasaur.bt.TorrentMetainfo
import org.ibiblio.terasaur.bencode.BencodeException
import org.ibiblio.terasaur.bt.TorrentServiceException

import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest
import org.springframework.web.multipart.commons.CommonsMultipartFile
import org.ibiblio.terasaur.bt.TorrentService
import org.codehaus.groovy.grails.commons.ApplicationHolder
import org.springframework.context.ApplicationContext
import org.apache.log4j.Logger

class AddTorrentCommand extends Command {
    private static final log = Logger.getLogger(this)

    public AddTorrentCommand(Map m) {
        super(m)
    }

    public Map run() {
        Map result
        String message

        // _params.filename
        // _params.torrent
        // _params.item_id
        // user id, credentials, or session information <-- how to make this work?

        try {
            TorrentService torrentService = _getTorrentService()
            result = torrentService.add(_params)
            log.info("Add torrent command processed for item id " + result.itemId)
        } catch (BencodeException e) {
            message = 'The torrent file was not valid'
        } catch (TorrentServiceException e) {
            log.error('TorrentServiceException: ' + e.message)
            message = e.message
        } catch (Exception e) {
            message = 'Error adding torrent'
            log.error("Add torrent command exception (" + e.class.name + "): " + e.message, e)
        }

        if (!result) {
            result = [message: message]
        }
        return result
    }

    private TorrentService _getTorrentService() {
        ApplicationContext ctx = (ApplicationContext)ApplicationHolder.getApplication().getMainContext()
        TorrentService s = (TorrentService)ctx.getBean("torrentService");
        return s
    }
}
